package com.wzy.mall.web.servlet.admin;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.mall.model.bo.adminBO.AdminBO;
import com.wzy.mall.model.bo.adminBO.AdminLoginBO;
import com.wzy.mall.model.bo.adminBO.AdminPwdBO;
import com.wzy.mall.model.pojo.adminPOJO.AdminPOJO;
import com.wzy.mall.model.vo.adminVO.AdminLoginVO;
import com.wzy.mall.model.vo.adminVO.AllAdminsVO;
import com.wzy.mall.model.vo.ResultVO;
import com.wzy.mall.service.admin.AdminService;
import com.wzy.mall.service.admin.impl.AdminServiceImpl;
import com.wzy.mall.utils.HTTPUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Admin {

    private static ObjectMapper jsonMapper = new ObjectMapper();

    private static AdminService adminService = new AdminServiceImpl();

    /**
     *  管理员登陆
     * @param request
     * @param response
     */
    public static void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 数据是JSON类型，不能直接获取参数键值对
            // 读取请求体
            String requestBody = HTTPUtils.getJSONRequest(request);

            // 将请求体数据JSON字符串封装成BO对象
            AdminLoginBO adminLoginBO = jsonMapper.readValue(requestBody, AdminLoginBO.class);
            //System.out.println(adminLoginBO);

            // 当用户名和密码其中一个为空时，直接返回10000和报错信息
            if(StringUtils.isEmpty(adminLoginBO.getEmail())) {
                ResultVO resultVO = new ResultVO(10000, null, "\r\n用户名不能为空哦~");
                // 将Java对象转换为JSON字符串
                response.getWriter().println(jsonMapper.writeValueAsString(resultVO));
                return;
            }
            if(StringUtils.isEmpty(adminLoginBO.getPwd())) {
                ResultVO resultVO = new ResultVO(10000, null, "\r\n密码不能为空哦~");
                response.getWriter().println(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 将数据交给Service层，与数据库交接
            Integer code = adminService.selectAdminByUsernameAndPassword(adminLoginBO);
            if(code == 200) {
                // 将登陆信息email存放在Session，用于通过后台拦截
                HttpSession requestSession = request.getSession();
                requestSession.setAttribute("email", adminLoginBO.getEmail());

                // 返回200表示查找到匹配账号，将数据封装到AdminLoginVO中
                AdminLoginVO adminLoginVO = new AdminLoginVO();
                adminLoginVO.setToken(adminLoginBO.getNickName());
                adminLoginVO.setName(adminLoginBO.getNickName());

                ResultVO resultVO = new ResultVO(0, adminLoginVO, null);
                //System.out.println(resultVO);
                // 转换为JSON字符串
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(code == 404) {
                // 404表示数据库中没有匹配的账号
                ResultVO resultVO = new ResultVO(10000, null, "\r\n用户名或密码错误哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(code == 500) {
                // 500表示服务器内错误
                ResultVO resultVO = new ResultVO(10000, null, "\r\n服务器繁忙，请稍后再试哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  查询所有管理员
     * @param request
     * @param response
     */
    public static void allAdmins(HttpServletRequest request, HttpServletResponse response) {
        // 调用Service层的方法查询所有管理员账号
        List<AdminPOJO> adminPOJOList = adminService.selectAllAdmins();

        // 创建管理员账号VO层对象的集合
        List<AllAdminsVO> allAdminsVOList = new ArrayList<AllAdminsVO>();
        // 遍历返回值，封装进集合
        for (AdminPOJO adminPOJO : adminPOJOList) {
            AllAdminsVO allAdminsVO = new AllAdminsVO();
            allAdminsVO.setId(adminPOJO.getId());
            allAdminsVO.setEmail(adminPOJO.getUsername());
            allAdminsVO.setPwd(adminPOJO.getPassword());
            allAdminsVO.setNickname(adminPOJO.getNickname());

            allAdminsVOList.add(allAdminsVO);
        }
        // 创建结果对象
        ResultVO resultVO = new ResultVO(0, allAdminsVOList, null);

        try {
            // 将结果对象输出到响应体
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  添加管理员
     * @param request
     * @param response
     */
    public static void addAdminss(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取请求体中的JSON数据
            String requestBody = HTTPUtils.getJSONRequest(request);
            // 将JSON字符串封装成BO对象
            AdminBO adminBO = jsonMapper.readValue(requestBody, AdminBO.class);

            // 判空
            if(StringUtils.isEmpty(adminBO.getEmail())) {
                ResultVO resultVO = new ResultVO(10000, null, "账号不能为空哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }
            if(StringUtils.isEmpty(adminBO.getNickname())) {
                ResultVO resultVO = new ResultVO(10000, null, "昵称不能为空哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }
            if(StringUtils.isEmpty(adminBO.getPwd())) {
                ResultVO resultVO = new ResultVO(10000, null, "密码不能为空哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 调用Service层，与数据库交互
            int result = adminService.addAdmin(adminBO);

            if(result == 1) {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "添加失败，换个名字试试吧~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据ID删除管理员
     * @param request
     * @param response
     */
    public static void deleteAdmins(HttpServletRequest request, HttpServletResponse response) {
        // 因为使用参数提交的，所以可以用这个方法获取
        String id = request.getParameter("id");

        int result = 0;
        try {
            result = adminService.deleteAdmin(Integer.parseInt(id));
            if(result == 1) {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if (result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "删除失败啦~~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     *  根据条件查询管理员
     * @param request
     * @param response
     */
    public static void ConditionalQuery(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求体中的JSON数据
        try {
            String requestBody = HTTPUtils.getJSONRequest(request);

            // 将JSON字符串封装成BO对象
            AdminBO adminBO = jsonMapper.readValue(requestBody, AdminBO.class);

            // 调用Service层 查询数据库
            List<AdminPOJO> adminPOJOList = adminService.selectByCondition(adminBO);

            ArrayList<AllAdminsVO> allAdminsVOList = new ArrayList<AllAdminsVO>();
            for (AdminPOJO adminPOJO : adminPOJOList) {
                AllAdminsVO allAdminsVO = new AllAdminsVO();
                allAdminsVO.setId(adminPOJO.getId());
                allAdminsVO.setEmail(adminPOJO.getUsername());
                allAdminsVO.setNickname(adminPOJO.getNickname());
                allAdminsVO.setPwd(adminPOJO.getPassword());

                allAdminsVOList.add(allAdminsVO);
            }

            ResultVO resultVO = new ResultVO(0, allAdminsVOList, null);
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) {
        // 获取Admin的id
        String id = request.getParameter("id");

        // 调用Service层 与数据库交互
        AdminPOJO adminPOJO = adminService.selectById(Integer.parseInt(id));
        // 将POJO对象转换为VO对象
        AllAdminsVO allAdminsVO = new AllAdminsVO();
        allAdminsVO.setId(adminPOJO.getId());
        allAdminsVO.setEmail(adminPOJO.getUsername());
        allAdminsVO.setNickname(adminPOJO.getNickname());
        allAdminsVO.setPwd(adminPOJO.getPassword());

        //System.out.println(allAdminsVO);

        try {
            // 生成结果集对象，封装成JSON数据
            ResultVO resultVO = new ResultVO(0, allAdminsVO, null);
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void updateAdminss(HttpServletRequest request, HttpServletResponse response) {
        // 从请求体获取JSON数据
        try {
            String requestBody = HTTPUtils.getJSONRequest(request);

            // 将JSON字符串转换为BO对象
            AdminBO adminBO = jsonMapper.readValue(requestBody, AdminBO.class);

            // 调用Service层 与数据库交互
            int result = adminService.updateById(adminBO);
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "修改失败啦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result != 0) {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  管理员修改密码
     * @param request
     * @param response
     */
    public static void changePwd(HttpServletRequest request, HttpServletResponse response) {
        // 获取JSON数据
        try {
            String requestBody = HTTPUtils.getJSONRequest(request);
            // 将JSON字符串转换为BO对象
            AdminPwdBO adminPwdBO = jsonMapper.readValue(requestBody, AdminPwdBO.class);
            //System.out.println(adminPwdBO);

            // 首先判断新密码是否为空
            String newPwd = adminPwdBO.getNewPwd();
            if(newPwd == null || "".equals(newPwd)) {
                ResultVO resultVO = new ResultVO(10000, null, "新密码不能为空啊啊啊");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 判断两次密码是否一致
            String confirmPwd = adminPwdBO.getConfirmPwd();
            if(!newPwd.equals(confirmPwd)) {
                ResultVO resultVO = new ResultVO(10000, null, "两次输入密码不一致啊啊啊");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 调用Service层
            int result = adminService.changePwd(adminPwdBO);
            if(result==404) {
                ResultVO resultVO = new ResultVO(10000, null, "没有找到该用户~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result == 401) {
                ResultVO resultVO = new ResultVO(10000, null, "旧密码不一致~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result == 500) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，修改失败~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result == 200) {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  管理员登出
     * @param request
     * @param response
     */
    public static void logoutAdmin(HttpServletRequest request, HttpServletResponse response) {
        // 清空Session中的数据
        HttpSession requestSession = request.getSession();
        requestSession.invalidate();

        // 不知道怎么处理，直接返回结果0
        ResultVO resultVO = new ResultVO(0, null, null);
        try {
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
